package com.sun.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sun.reggie.common.R;
import com.sun.reggie.entity.Employee;
import com.sun.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * @author sun
 * @version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    EmployeeService employeeService;

    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpServletRequest request){
        log.info("username:{},password:{}",employee.getUsername(),employee.getPassword());
        //将密码加密
        String md5password = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());
        //将用户名传入到数据库中，进行查询，检验该用户名是否存在
        String username = employee.getUsername();

        //getOne() 通过用户名获取1个员工对象
        QueryWrapper<Employee> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);

        Employee one = (Employee) employeeService.getOne(wrapper);
        if (one==null){
            return  R.error("查无此用户");
        }
        //如果one存在，数据中有数据
        //通过one 获取数据库中的密文
        String password = one.getPassword();

        if (md5password==null||!md5password.equals(password)){
            return  R.error("密码错误，请重新输入");
        }

        Integer status = one.getStatus();
        if (status==0){
            return  R.error("此用户已经禁用，请联系管理员");
        }

        //如果登陆成功，将用户id 存到服务器的session中
        request.getSession().setAttribute("employee",one.getId());
        return R.success(one);
    }




    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
//    退出的逻辑： 客户端发起一个退出请求，告诉服务端，删除session

        request.getSession().removeAttribute("employee");

        return R.success("logout ok");
    }


    @PostMapping
    public R<String>save(@RequestBody Employee employee,HttpServletRequest request){

        String username = employee.getUsername();
        QueryWrapper<Employee> employeeQueryWrapper = new QueryWrapper();
        employeeQueryWrapper.eq("username",username);
        Employee one = employeeService.getOne(employeeQueryWrapper);
        if(one != null){
            return R.error(username+"用户名存在，请更换");
        }

        String newPassword = DigestUtils.md5DigestAsHex("123456".getBytes());
        employee.setPassword(newPassword);
        employee.setStatus(1);
        Long employeeId = (Long) request.getSession().getAttribute("employee");
       // employee.setCreateTime(LocalDateTime.now());
        //employee.setUpdateTime(LocalDateTime.now());
        //employee.setCreateUser(employeeId);
       // employee.setUpdateUser(employeeId);

        boolean isSave = employeeService.save(employee);
        return isSave?R.success("添加成功"):R.error("添加失败");

    }


    @GetMapping("/page")
    public R<Page> page(Integer page,Integer pageSize,String name){
        log.info("当前页：{} 每页{}条，检索关键词：{}",page,pageSize,name);
        //分页构造器，传入当前页码和每页多少条
        Page<Employee> employeePage = new Page<>(page,pageSize);
//        构建条件查询器。模糊查询

        QueryWrapper<Employee> wrapper = new QueryWrapper<>();
        wrapper.like(name!=null,"username",name)
                .or()
                .like(name!=null,"name",name);

//        开始分页查询
        employeeService.page(employeePage,wrapper);

        return R.success(employeePage);
    }

    @PutMapping
    public R<String> updateStatus(@RequestBody Employee employee,HttpServletRequest request){

        log.info("禁用启用：id：{}，status：{}",employee.getId(),employee.getStatus());
//        禁用启用本质就是修改数据
        employee.setUpdateTime(LocalDateTime.now());


        Long employeeId = (Long) request.getSession().getAttribute("employee");

//        设置修改者
        if (employeeId!=null){
            employee.setUpdateUser(employeeId);
        }

//        调用service修改
        boolean updateStatus = employeeService.updateById(employee);



        return updateStatus?R.success("操作成功"):R.error("操作失败");
    }

    /**
     * 根据id查询员工信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id){
        log.info("根据id查询员工信息...");
        Employee employee = employeeService.getById(id);
        if(employee != null){
            return R.success(employee);
        }
        return R.error("没有查询到对应员工信息");
    }


    /**
     * 根据id修改员工信息
     * @param employee
     * @return
     */
    @PutMapping("/enable")
    public R<String> update( @RequestBody Employee employee){
        log.info(employee.toString());

        //Long empId = (Long)request.getSession().getAttribute("employee");

        //employee.setUpdateTime(LocalDateTime.now());
        //employee.setUpdateUser(empId);
        employeeService.updateById(employee);

        return R.success("员工信息修改成功");
    }
}
